<template>
  <div class="controls">
    <input
      autocomplete="off"
      class="itxt"
      :value="currentValue"
      @blur="handleInputEvnet"
      @keyup.enter="handleInputEvnet"
    />
    <button
      class="plus"
      @click="setCurrentValue(1)"
      :disabled="currentValue === max"
    >
      +
    </button>
    <button
      class="mins"
      @click="setCurrentValue(-1)"
      :disabled="currentValue === min"
    >
      -
    </button>
  </div>
</template>

<script>
export default {
  name: 'InputNumber',
  props: {
    value: {
      type: Number,
      required: true,
    },
    min: {
      type: Number,
      default: 1,
    },
    max: {
      type: Number,
      default: 20,
    },
  },
  data() {
    return {
      currentValue: this.value,
    }
  },
  methods: {
    setCurrentValue(num) {
      this.currentValue += num
    },
    handleInputEvnet(e) {
      this.currentValue = e.target.value
    },
  },
  watch: {
    currentValue(newVal, oldVal) {
      const { min, max } = this
      let newValue = Math.ceil(+newVal)

      if (Number.isNaN(newValue)) {
        newValue = oldVal
      }

      if (newValue < min) {
        newValue = min
      } else if (newValue > max) {
        newValue = max
      }

      this.currentValue = newValue
      this.$emit('input', newValue)
    },
  },
}
</script>

<style lang="less" scoped>
.controls {
  width: 48px;
  position: relative;
  float: left;
  margin-right: 15px;

  .itxt {
    width: 38px;
    height: 37px;
    border: 1px solid #ddd;
    color: #555;
    float: left;
    border-right: 0;
    text-align: center;
  }

  .plus,
  .mins {
    width: 15px;
    text-align: center;
    height: 17px;
    line-height: 17px;
    background: #f1f1f1;
    color: #666;
    position: absolute;
    right: -8px;
    border: 1px solid #ccc;
    cursor: pointer;
  }

  .mins {
    right: -8px;
    top: 19px;
    border-top: 0;
  }

  .plus {
    right: -8px;
  }

  .plus:disabled,
  .mins:disabled {
    color: #ccc;
    cursor: not-allowed;
  }
}
</style>
